<template>
	<view class="main">
		<message-index :isShow="PageCur=='message'?true:false" ></message-index>
		<contacts-index :isShow="PageCur=='contacts'?true:false" ></contacts-index>
		<discover-index :isShow="PageCur=='discover'?true:false" ></discover-index>
		<me-index :isShow="PageCur=='me'?true:false" ></me-index>
		<common-view :indicator="indicator" :animationClass="animation" :message="indicatorMsg" :zindex="1111"
			@closeAnimation="closeAnimation"></common-view>
		<view class="cu-bar tabbar bg-nav foot">
			<view class="action" @click="NavChange" data-cur="message">
				<view class='icon-cu-image'>
					<image :src="'/static/nav-icon-msg' + [PageCur=='message'?'.active':''] + '.png'"></image>
					<view v-if="unreadMsgCount" class="cu-tag badge">{{unreadMsgCount}}</view>
				</view>
				<view :class="PageCur=='message'?'text-themeColor':'text-baseColor'">消息</view>
			</view>
			<view class="action" @click="NavChange" data-cur="contacts">
				<view class='icon-cu-image'>
					<image :src="'/static/nav-icon-contacts' + [PageCur=='contacts'?'.active':''] + '.png'"></image>
					<!-- <view class="cu-tag badge badge-0"></view> -->
				</view>
				<view :class="PageCur=='contacts'?'text-themeColor':'text-baseColor'">通讯录</view>
			</view>
			<view class="action" @click="NavChange" data-cur="discover">
				<view class='icon-cu-image'>
					<image :src="'/static/nav-icon-discover' + [PageCur=='discover'?'.active':''] + '.png'"></image>
					<!-- <view class="cu-tag badge badge-0"></view> -->
				</view>
				<view :class="PageCur=='discover'?'text-themeColor':'text-baseColor'">发现</view>
			</view>
			<view class="action" @click="NavChange" data-cur="me">
				<view class='icon-cu-image'>
					<image :src="'/static/nav-icon-me' + [PageCur == 'me'?'.active':''] + '.png'"></image>
					<!-- <view class="cu-tag badge badge-0"></view> -->
				</view>
				<view :class="PageCur=='me'?'text-themeColor':'text-baseColor'">我</view>
			</view>
		</view>
		<view class="cu-modal" :class="(!hasLogin && (needLogin || PageCur == 'user'))?'show':''" catchtouchmove="false"
			style="background:#f7f7f7;display:flex;justify-content:center;align-items:center;z-index:998;">
			<view style="position:absolute;" class="login-box" :style="'top:'+barHeight+'px;width:100%;'">
				<view class="login-logo">
					<image src="../../static/logo.png" style="width:230upx;height:230upx;"></image>
					<view class="text-baseColor text-30 text-bold" style="line-height:60upx;">XXX-CHAT</view>
				</view>
			</view>
			<view class="btn-list">
				<view class="padding-bottom-safe">
					<view class="padding-lg" style="padding-top: 0;">
						<navigator class="cu-btn block bg-them round text-bold lg" style="font-size:26upx;" url="../../pages1/login/mobile">
							<image src="../../static/pwd_w.png" style="width:30upx;height:30upx;margin-right:5upx;"></image> 账号密码登录
						</navigator>
					</view>
					<view class="padding-lg" style="padding-top: 0;">
						<navigator class="cu-btn block lines-themeColor round text-bold lg" style="font-size:26upx;" url="../../pages1/login/captcha">
							<image src="../../static/captcha.png" style="width:30upx;height:30upx;margin-right:5upx;"></image> 验证码登录
						</navigator>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import userObj from 'model/userModel.js';
	import xcxObj from 'model/xcxModel.js'
	let disp = require("common/broadcast");
	let me = null;
	export default {
		data() {
			return {
				PageCur: 'message',
				defPageCur:'message',
				StatusBar: this.StatusBar,
				indicator: 0,
				indicatorMsg: '',
				animation: '',
				isReady: 0,
				needJump: 0,
				needLogin: 1,
				netError: 0,
				reloading: 0,
				jumpUrl: '',
				isWXInstalled: 0,
				opts: {},
				need_update: 0,
				downloadProgress: 0,
				version: null,
				toReboot: 0,
				barHeight: 0,
				backBtnWidth: 0,
				newVersionInfo: '',
				tabHistory: ['message', 'contacts', 'discover', 'me'],
				defTabHistory: ['message', 'contacts', 'discover', 'me'],
			}
		},
		onLoad(option) {
			console.log('main onLoad...')
			me = this;
			if(me.getStore('referrerId')){
				this['baseModule/setReferrerId'](me.getStore('referrerId'));
			}

			this.barHeight = this.CustomBar;
			this.backBtnWidth = uni.upx2px(100);
			me.opts = option;
			if (option.scene) {
				console.log(option.scene);
				var sceneP = JSON.parse(('{' + decodeURIComponent(option.scene) + '}').replace(
					/(?:\s*['"]*)?([a-zA-Z0-9]+)(?:['"]*\s*)?:/g, '"$1":'));
				console.log(sceneP);
				if (sceneP.rid && me.referrerId==0) {
					me.setStore("referrerId", sceneP.rid);
					this['baseModule/setReferrerId'](sceneP.rid);
				}
				if (sceneP.stid){
					this.indicator = 3;
					this.needJump = 1;
					this.jumpUrl = "../../pages/goods/detail?standard_id="+sceneP.stid
				}
				else if (sceneP.sid) {
					this.indicator = 3;
					this.needJump = 1;
					this.jumpUrl = "../../pages/supplier/index?supplier_id=" + sceneP.sid
				}
			}
			
			if (option.referrer_id && me.referrerId==0) {
				me.setStore("referrerId", option.referrer_id);
				this['baseModule/setReferrerId'](option.referrer_id);
			}
			if (option.tab) {
				me.PageCur = option.tab;
			}
			disp.on("changePageCur", function(pageCur) {
				me.PageCur = pageCur;
				me.removeByValue(me.tabHistory, me.PageCur);
				me.tabHistory.unshift(me.PageCur);
			});
			disp.on("toLogin", function() {
				me.needLogin = 1;
			});

			//#ifdef APP-PLUS
			me.push_msg_handle();
			//#endif

			// #ifdef APP-PLUS
			if (plus.networkinfo.getCurrentType() < 2) {
				plus.navigator.closeSplashscreen();
				me.netError = 1;
			}
			// #endif
		},
		onShow() {
			console.log('main onShow...')
			if (this.isReady) {
				disp.fire("refreshCart");
				// #ifdef MP-WEIXIN || MP-TOUTIAO
				me.jump();
				// #endif
			}
		},
		onShareAppMessage() {
			if(me.hasLogin){
				return {
				      title: me.appName+",昆明本地鲜花批发平台",
				      path: '/pages/main/index?scene=rid:'+me.userInfo.user_id
				    }
			}
			else{
				return {
				      title: me.appName+",昆明本地鲜花批发平台",
				      path: '/pages/main/index'
				    }
			}
		},
		onShareTimeline(){
			if(me.hasLogin){
				return {
				      title: me.appName+",昆明本地鲜花批发平台",
				      query: 'fromTimeLine=1&referrer_id='+me.userInfo.user_id
				    }
			}else{
				return {
				      title: me.appName+",昆明本地鲜花批发平台",
				      query: 'fromTimeLine=1'
				    }
			}
			
		},
		onReady() {

			this.isReady = 1;
			console.log('main onReady...')

			// #ifdef MP-WEIXIN || MP-TOUTIAO
			me.jump();
			// #endif
			
		},
		onHide() {
			console.log('main onHide...')
		},
		onUnload() {
			console.log('main onUnload...')
		},
		computed: {
			...mapState({
				appConfig: ({
					baseModule
				}) => baseModule.appConfig,
				hasLogin: ({
					userModule
				}) => userModule.hasLogin,
				userInfo: ({
					userModule
				}) => userModule.userInfo,
				msgBadge: ({
					baseModule
				}) => baseModule.msgBadge,
				cartBadge: ({
					baseModule
				}) => baseModule.cartBadge,
				navUserTip: ({
					baseModule
				}) => baseModule.navUserTip,
				unreadMsgCount: ({
					chatModule
				}) => chatModule.unreadMsgCount,
				dToken: ({
					baseModule
				}) => baseModule.dToken,
				dClientid: ({
					baseModule
				}) => baseModule.dClientid,
				chatWindowsId: ({
					chatModule
				}) => chatModule.chatWindowsId,
				referrerId: ({
					baseModule
				}) => baseModule.referrerId
			})
		},
		methods: {
			...mapMutations(['baseModule/setReferrerId', 'baseModule/setDClientid',
				'baseModule/setDToken', 'chatModule/setChatTo','userModule/login','userModule/setOpenId','userModule/setUnionId'
			]),
			closeAnimation() {
				this.animation = "";
				this.indicator = 0;
			},
			removeByValue(arr, val) {
				for (var i = 0; i < arr.length; i++) {
					if (arr[i] == val) {
						arr.splice(i, 1);
						break;
					}
				}
			},
			NavChange(e) {
				this.PageCur = e.currentTarget.dataset.cur;
				this.removeByValue(this.tabHistory, this.PageCur);
				this.tabHistory.unshift(this.PageCur);
				// console.log(this.tabHistory);

			},
			denyAuthorization(e) {
				this.needLogin = 0;
				this.PageCur = this.tabHistory[1];
			},
			showQr(imgUrl){
				uni.previewImage({
					current: 0,
					urls: [me.appConfig.wx_group_qr]
				});
			},
			xcxUpdate() {
				const updateManager = uni.getUpdateManager();
				updateManager.onUpdateReady(function(res) {
					uni.showModal({
						title: '更新提示',
						content: '新版本已经准备好，是否重启应用？',
						showCancel :false,
						success(res) {
							if (res.confirm) {
								updateManager.applyUpdate();
							}
						}
					});

				});
			},
			jump() {
				if (me.needJump) {
					uni.navigateTo({
						url: me.jumpUrl,
						complete:function(e){
							var f = function() {
								me.indicator = 0;
								clearInterval(t);
							};
							var t = setInterval(f, 1000);
							me.needJump = 0;
						}
					})
					
				}
				else{
					me.xcxUpdate();
				}
			},
			reboot(){
				plus.runtime.restart();
			},
			reload() {
				me.indicatorMsg = "正在检查网络";
				me.indicator = 5;
				me.reloading = 1;

				var reNum = 0;
				var f = function() {
					reNum = reNum + 1;
					if (plus.networkinfo.getCurrentType() > 1) {
						clearInterval(t);
						uni.reLaunch({
							url: 'index'
						});
					}
					else{
						if(reNum>30){
							me.indicator = 0;
							clearInterval(t);
						}
					}
					console.log(reNum);
				};
				var t = setInterval(f, 1000);
				
			},
			push_msg_handle() {
				const _handlePush = function(msg) {
					console.log("_handlePush:" + JSON.stringify(msg));
					var payload = {};
					if (typeof msg.payload == 'string') {
						payload = JSON.parse(msg.payload)
					}
					else{
						payload = msg.payload;
					}
					//console.log(payload);
					if (payload.event == 'chat' && payload.url == 'chat' && me.chatWindowsId == 0 && me.hasLogin) {
						var to = {};
						to.id = payload.friendid;
						to.name = payload.username;
						to.avatar = payload.avatar;
						to.type = 'friend';
						me['chatModule/setChatTo'](to);
						uni.navigateTo({
							url: "../../pages1/message/chat?friendid=" + payload.friendid + "&unread=0"
						});
					}
					else{
						uni.navigateTo({
							url: payload.url
						});
					}
					if (payload.event == 'none') {

					}
				};
				plus.push.addEventListener('click', _handlePush);
				plus.push.addEventListener('receive', _handlePush);
			},
			
			xcxGetUserProfile() {
				uni.showLoading({
					title: '请稍后'
				});
				wx.getUserProfile({
					desc:'获取头像、昵称',
					success: function(res2) {
						var _wxxcxInfo = JSON.parse(res2.rawData);
						me.setStore("wxxcxInfo",_wxxcxInfo);
						wx.login({
						  success (res1) {
						    if (res1.code) {
							  uni.showLoading({
							  	title: '加载中'
							  });
							  xcxObj.getUserInfo(me,{
								code: res1.code,
							  	iv: res2.iv,
							  	encryptedData: res2.encryptedData,
							  	referrerId: me.referrerId
							  }).then(resData=>{
							  	if(resData.userInfo){
							  		me['userModule/login'](resData.userInfo);
							  		me['userModule/setOpenId'](resData.openId);
									me['userModule/setUnionId'](resData.unionId);
							  		me.setUserInfo(resData.userInfo);
							  		me.setStore("openId", resData.openId);
									me.setStore("unionId", resData.unionId);
							  		uni.hideLoading();
							  	}
							  	else{
							  		me.setStore("openId", resData.openId);
									me.setStore("unionId", resData.unionId);
									_wxxcxInfo.openId = resData.openId;
									_wxxcxInfo.unionId = resData.unionId;
									me.setStore("wxxcxInfo",_wxxcxInfo);
							  		uni.navigateTo({
							  			url:'../../pages1/login/wxxcxBanding'
							  		})
							  	}
							  	uni.hideLoading();
							  }).catch(err=>{
							  	console.log('error:' + err)
							  	uni.hideLoading();
							  	uni.showToast({
							  		title: '授权登录失败',
							  		icon: 'none',
							  		duration: 1000
							  	});
							  });
						    } else {
						      console.log('登录失败:' + res1.errMsg);
							  uni.showToast({
							  	title: '授权登录失败',
							  	icon: 'none',
							  	duration: 1000
							  });
						    }
						  }
						});
					},
					fail: function(errorMsg) {
						console.log('获取用户登录态失败:' + errorMsg)
						uni.hideLoading();
						uni.showToast({
							title: '授权登录失败',
							icon: 'none',
							duration: 1000
						});
					}
				});
			}
		},
		onBackPress(options) {
			if (this.tabHistory[1] != this.defPageCur && this.PageCur != this.defPageCur) {
				this.PageCur = this.tabHistory[1];
				this.removeByValue(this.tabHistory, this.PageCur);
				this.tabHistory.push(this.PageCur);
				return true;
			} else {
				this.PageCur = this.defPageCur;
				this.tabHistory = this.defTabHistory;
			}
		}
	}
</script>

<style>

</style>
